package purchasePlan

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"
	"time"

	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type CancelPurchasePlanApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCancelPurchasePlanApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CancelPurchasePlanApiLogic {
	hostname, _ := os.Hostname()
	return &CancelPurchasePlanApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CancelPurchasePlanApiLogic) CancelPurchasePlanApi(req *types.CancelPurchasePlanReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	planEntities, err := dao.PurchasePlanEntity.WithContext(l.ctx).Where(dao.PurchasePlanEntity.ID.In(req.IdList...)).Find()
	if err != nil || len(planEntities) == 0 {
		return "", errors.New("传递的主键错误")
	}
	var purchasePlanIdList = make([]int64, 0)
	for _, item := range planEntities {
		purchasePlanOrders, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdApi(l.ctx, item.ID)
		if err != nil {
			return "", errors.New("系统错误，取消失败")
		}
		if item.Status != 0 || len(purchasePlanOrders) > 0 {
			return "", errors.New("仅“待采购”且未关联订单的计划可取消")
		}
		purchasePlanIdList = append(purchasePlanIdList, item.ID)
	}
	purchasePlanOrdersEntity, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdListApi(l.ctx, k.Distinct(purchasePlanIdList))
	if err != nil && len(purchasePlanOrdersEntity) > 0 {
		return "", errors.New("该计划已关联客户订单，无法取消")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	if _, err = tx.PurchasePlanEntity.WithContext(l.ctx).Where(dao.PurchasePlanEntity.ID.In(req.IdList...)).UpdateSimple(
		dao.PurchasePlanEntity.Status.Value(30),
		dao.PurchasePlanEntity.CancelReason.Value(req.CancelReason),
	); err != nil {
		logx.Errorf("修改采购计划单状态失败:%v", err)
		err = tx.Rollback()
		return "", errors.New("取消失败")
	}
	// 订单详情里面操作
	purchaserIdList := k.Map(planEntities, func(item *model.PurchasePlanEntity, index int) int64 {
		return item.PurchaserID
	})
	planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailByPlanIdListApi(l.ctx, purchaserIdList)
	if err == nil && len(planOrdersEntities) > 0 {
		orderDetailIdList := k.Map(planOrdersEntities, func(item *model.PurchasePlanOrdersEntity, index int) int64 {
			return item.OrdersDetailsID
		})
		if _, err = tx.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.ID.In(orderDetailIdList...)).UpdateSimple(
			dao.OrdersDetailEntity.Status.Value(-1),
		); err != nil {
			logx.Errorf("修改订单详情状态失败:%v", err)
			tx.Rollback()
			return "", errors.New("取消失败")
		}
		// TODO 后期改消息队列，判断当前订单状态是否全部改为取消了
		time.AfterFunc(2*time.Second, func() {
			detailEntities, err := dao.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.ID.In(orderDetailIdList...)).Find()
			if err != nil || len(detailEntities) == 0 {
				return
			}
			orderIdList := k.Map(detailEntities, func(item *model.OrdersDetailEntity, index int) int64 {
				return item.OrdersID
			})
			ordersDetailEntities, err := dao.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.OrdersID.In(orderIdList...)).Find()
			if err != nil || len(ordersDetailEntities) == 0 {
				return
			}
			orderDetailStatusMap := k.GroupBy(ordersDetailEntities, func(item *model.OrdersDetailEntity) int64 {
				return item.OrdersID
			})
			// 取消订单
			for key, value := range orderDetailStatusMap {
				if len(value) == 1 && value[0].Status == enum.OrdersCancelEnum {
					if _, err = dao.OrdersEntity.WithContext(l.ctx).Where(dao.OrdersEntity.ID.Eq(key)).UpdateSimple(
						dao.OrdersEntity.Status.Value(enum.OrdersCancelEnum),
					); err != nil {
						logx.Errorf("取消订单状态失败:%v", err)
					}
				}
			}
		})
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("操作失败")
	}
	return "取消成功", nil
}
